const mysql = require('../db/mysql57');
const minio = require('../db/minio');

const config = require('../config');

const loginDao = {
    // 通过openid进行登录
    async loginByOpenid(openid) {
        let sql = `select
                u.id as id,
                u.username as name,
                u.avaterId as avaterId,
                u.gender as gender,
                u.phone as phone,
                u.email as email,
                u.bio as bio,
                u.school as school,
                u.major as major,
                u.grade as grade,
                u.balance as balance,
                u.points as points,
                u.level as level
            from
                User as u
            where openid = ? Limit 1`;
        let data = [ openid ];
        return mysql.sqlExec(sql, data);
    },
    // 注册用户
    async addUser(openid, wxLogin) {
        // 尝试开启事务
        let sql1;
        let data1;
        let uid;
        let connection;
        let result;
        let browser = config.minio.avaterBrower;
        let uri = '';
        let avaterId;
        try {
            connection = await mysql.startTransaction();
        } catch (error) {
            throw error;
        }

        // 判断是否有头像
        if (wxLogin.userInfo.avatarBuffer) {
            // 往 PublicImg 表中插入数据
            try {
                let status = '待上传';
                let sql = `insert into PublicImg (browser, uri, status) VALUES (?, ?, ?)`;
                let data = [browser, uri, status];
                result = await mysql.sqlExecInTransaction(connection, sql, data);
            } catch (error) {
                await mysql.rollbackTransaction(connection);
                throw error;
            }
    
            // 往 MinIO 中上传图片（这个操作应该要封装到 minio 驱动里，后续修改）
            try {
                let buffer = wxLogin.userInfo.avatarBuffer;
                uri = `${result.insertId}.jpg`;
                await new Promise((resolve, reject) => {
                    minio.minio.putObject(browser, uri, buffer, buffer.length, async function (err, etag) {
                        if (err) {
                            reject(err);
                            return ;
                        } else {
                            resolve(true);
                        }
                    });
                });
            } catch (err) {
                await mysql.rollbackTransaction(connection);
                throw err;
            }
            // 更新 mysql 数据库中 图片的上传状态
            try {
                let sql = `update PublicImg set status = ?, uri = ? where id = ?`;
                let data = ['已完成', uri, result.insertId];
                await mysql.sqlExecInTransaction(connection, sql, data);
                avaterId = result.insertId;
                sql1 = `insert into User(
                        openid, username, avaterId, gender, userTypeId
                    ) values(?, ?, ?, ?, (
                        select id from UserType where name = ? LIMIT 1
                    ))`;
                data1 = [ openid, wxLogin.userInfo.nickName, avaterId, wxLogin.userInfo.gender, 'miniUser' ];
            } catch (err) {
                await mysql.rollbackTransaction(connection);
                throw err;
            }
        } else {
            avaterId = 1;
            sql1 = `insert into User(
                    openid, username, avaterId, gender, userTypeId
                ) VALUES (?, ?, ?, ?, (
                    select id from UserType where name = ? LIMIT 1
                ))`;
            data1 = [ openid, wxLogin.userInfo.nickName, avaterId, wxLogin.userInfo.gender, 'miniUser' ];
        }
        // 尝试注册用户
        try {
            result = await mysql.sqlExecInTransaction(connection, sql1, data1);
            uid = result.insertId;
        } catch (err) {
            throw err;
        }
        // 记录用户的新头像到用户历史头像表里
        try {
            let sql = `INSERT INTO HistoryUserAvater (uid, imgId) VALUES (?, ?)`;
            let data = [ uid, avaterId ];
            await mysql.sqlExecInTransaction(connection, sql, data);
        } catch (err) {
            await mysql.rollbackTransaction(connection);
            throw err;
        }
        // 查询用户的基本信息
        try {
            let sql = `select
                    u.id as id,
                    u.username as name,
                    u.avaterId as avaterId,
                    u.gender as gender,
                    u.phone as phone,
                    u.email as email,
                    u.bio as bio,
                    u.school as school,
                    u.major as major,
                    u.grade as grade,
                    u.balance as balance,
                    u.points as points,
                    u.level as level
                from
                    User as u
                where openid = ? Limit 1`;
            let data = [ openid ];
            result = mysql.sqlExecInTransaction(connection, sql, data);
        } catch (err) {
            throw err;
        }
        // 提交事务
        try {
            mysql.commitTransaction(connection);
        } catch (error) {
            await mysql.rollbackTransaction(connection);
            throw error;
        }
        // 返回数据
        return result;
    },
};

module.exports = loginDao;
